#!/usr/bin/env node

const { spawn, exec } = require('child_process');
const path = require('path');
const fs = require('fs');

// 颜色输出
const colors = {
  reset: '\x1b[0m',
  bright: '\x1b[1m',
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  magenta: '\x1b[35m',
  cyan: '\x1b[36m'
};

function log(message, color = 'reset') {
  console.log(`${colors[color]}${message}${colors.reset}`);
}

function logError(message) {
  log(`❌ ${message}`, 'red');
}

function logSuccess(message) {
  log(`✅ ${message}`, 'green');
}

function logInfo(message) {
  log(`ℹ️  ${message}`, 'blue');
}

function logWarning(message) {
  log(`⚠️  ${message}`, 'yellow');
}

// 检查依赖是否安装
function checkDependencies(dir, name) {
  return new Promise((resolve, reject) => {
    const nodeModulesPath = path.join(dir, 'node_modules');
    
    if (!fs.existsSync(nodeModulesPath)) {
      logWarning(`${name} 依赖未安装，正在安装...`);
      const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
      const install = spawn(npm, ['install'], { 
        cwd: dir, 
        stdio: 'inherit' 
      });
      
      install.on('close', (code) => {
        if (code === 0) {
          logSuccess(`${name} 依赖安装完成`);
          resolve();
        } else {
          logError(`${name} 依赖安装失败`);
          reject(new Error(`${name} 依赖安装失败`));
        }
      });
    } else {
      logSuccess(`${name} 依赖已存在`);
      resolve();
    }
  });
}

// 启动服务
function startService(dir, command, name, port) {
  return new Promise((resolve, reject) => {
    const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
    const args = command.split(' ');
    
    logInfo(`启动 ${name} 服务...`);
    
    const child = spawn(npm, args, {
      cwd: dir,
      stdio: 'pipe',
      shell: true
    });
    
    // 监听输出
    child.stdout.on('data', (data) => {
      const output = data.toString();
      if (output.includes('Local:') || output.includes('listening')) {
        logSuccess(`${name} 服务启动成功 - http://localhost:${port}`);
        resolve(child);
      }
      process.stdout.write(`[${name}] ${output}`);
    });
    
    child.stderr.on('data', (data) => {
      process.stderr.write(`[${name}] ${data}`);
    });
    
    child.on('error', (error) => {
      logError(`${name} 服务启动失败: ${error.message}`);
      reject(error);
    });
    
    child.on('close', (code) => {
      if (code !== 0) {
        logError(`${name} 服务异常退出，退出码: ${code}`);
      }
    });
    
    // 超时处理
    setTimeout(() => {
      if (!child.killed) {
        logWarning(`${name} 服务启动超时，但可能仍在启动中...`);
        resolve(child);
      }
    }, 10000);
  });
}

// 主函数
async function main() {
  try {
    log('========================================', 'bright');
    log('启动 Nuxt3 前端 + Node.js 后端服务', 'bright');
    log('========================================', 'bright');
    log('');
    
    // 检查Node.js版本
    const nodeVersion = process.version;
    logInfo(`Node.js 版本: ${nodeVersion}`);
    log('');
    
    // 检查依赖
    await checkDependencies('.', '前端');
    await checkDependencies('./backend', '后端');
    log('');
    
    log('========================================', 'bright');
    log('服务信息:', 'bright');
    log('前端服务: http://localhost:3000', 'cyan');
    log('后端服务: http://localhost:3002', 'cyan');
    log('后端健康检查: http://localhost:3002/health', 'cyan');
    log('========================================', 'bright');
    log('');
    
    // 启动后端服务
    const backendProcess = await startService('./backend', 'run dev', '后端', 3002);
    
    // 等待后端启动
    logInfo('等待后端服务完全启动...');
    await new Promise(resolve => setTimeout(resolve, 3000));
    
    // 启动前端服务
    const frontendProcess = await startService('.', 'run dev', '前端', 3000);
    
    log('');
    log('========================================', 'bright');
    log('🎉 所有服务启动完成！', 'green');
    log('');
    log('前端服务: http://localhost:3000', 'cyan');
    log('后端服务: http://localhost:3002', 'cyan');
    log('');
    log('按 Ctrl+C 停止所有服务', 'yellow');
    log('========================================', 'bright');
    
    // 处理退出信号
    const cleanup = () => {
      log('');
      logWarning('正在关闭所有服务...');
      
      if (backendProcess && !backendProcess.killed) {
        backendProcess.kill('SIGTERM');
      }
      
      if (frontendProcess && !frontendProcess.killed) {
        frontendProcess.kill('SIGTERM');
      }
      
      logSuccess('所有服务已关闭');
      process.exit(0);
    };
    
    process.on('SIGINT', cleanup);
    process.on('SIGTERM', cleanup);
    
    // 等待进程结束
    await Promise.all([
      new Promise(resolve => backendProcess.on('close', resolve)),
      new Promise(resolve => frontendProcess.on('close', resolve))
    ]);
    
  } catch (error) {
    logError(`启动失败: ${error.message}`);
    process.exit(1);
  }
}

// 运行主函数
main(); 